<template>
  <div class="users-container">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      <el-breadcrumb-item>用户详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索栏 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="querys.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息表格 -->
      <el-table border stripe :data="usersList" style="width: 100%">
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!--  slot-scope="scope" -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.id)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRole(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="alloRolesDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="querys.pagenum" :page-sizes="[2, 5, 8, 10]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="closeEvent" width="50%">
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" type="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editdFormrules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="alloRolesDialogVisible" width="50%" @close="alloRolesClose">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="newRole" placeholder="请选择角色">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="alloRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alloRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UsersPage',
  data () {
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9])+/
      if (regEmail.test(value)) return callback()
      callback(new Error('请输入合法的邮箱！'))
    }
    // 验证手机号的自定义
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]14[57])[0-9]{8}$/
      if (regMobile.test(value)) return callback()
      callback(new Error('请输入合法的手机号！'))
    }
    return {
      usersList: [],
      querys: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      total: 0, // 总记录数
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加角色数据对象
      addForm: {
        username: '',
        passwrd: '',
        email: '',
        mobile: ''
      },
      // 并编辑用户信息对像
      editForm: {},
      // 验证规则
      addFormrules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
        { max: 10, min: 3, message: '用户名长度为3-10个字符', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
        { max: 16, min: 6, message: '用户名长度为6-16个字符', trigger: 'blur' }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' }]
      },
      editdFormrules: {
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' }]
      },
      // 分配角色面板
      alloRolesDialogVisible: false,
      // 当前选中用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 当前选中角色
      newRole: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    // 获取用户列表
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.querys
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.usersList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 改变每页显示数量
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.querys.pagesize = newSize
      this.getUsersList()
    },
    // 改变当前页
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.querys.pagenum = newPage
      this.getUsersList()
    },
    // 改变状态
    async changeState (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      // console.log(res)
      if (res.mata.msg !== 200) {
        // 后台更新失败  视图得改回来
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败，请重试！')
      }
      this.$message.success('更新状态成功！')
    },
    // 对话框关闭事件
    closeEvent () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色
    addRole () {
      // 手动验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发送请求
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        // 判断是否响应陈工
        if (res.meta.status !== 201) return this.$message.error('操作失败！')
        this.$message.success('操作成功！')
        // 关闭弹窗
        this.addDialogVisible = false
        // 重新获取数据
        this.getUsersList()
      })
    },
    // 获取要编辑用户的 id
    // users/:id
    async editDialog (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败！')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息
    updateUserInfo () {
      // 调用表单验证
      this.$refs.editFormRef.validate(async valid => {
        // 验证成功修改数据
        if (!valid) return false
        // 验证成功则修改数据
        // users/:id
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
        // 关闭弹窗
        this.editDialogVisible = false
        // 重新获取用户信息数据
        this.getUsersList()
        // 提示修改成功
        this.$message.success('信息修改成功！')
      })
    },
    // 删除用户
    async delRole (id) {
      // 提示是否确认操作
      // 此处有问题  id传不进去
      // this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(async id => {
      //   console.log(id)
      //   // 发送请求
      //   const res = await this.$http.delete(`users/${id}`)
      //   console.log(res)
      //   // 判断是否请求响应陈功
      //   if (res.meta.status !== 200) return this.$message('操作失败，请稍后重试！')
      //   // 重新加载列表
      //   this.getUsersList()
      //   // 提示操作成功
      //   this.$message.success('删除成功!')
      // }).catch(() => {
      // // 判断操作失败则提示
      //   this.$message.info('已取消删除')
      // })
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      if (result !== 'confirm') return this.$message.info('已取消删除！')
      // 点击确认得到 confirm
      // 发送请求
      const { data: res } = await this.$http.delete(`users/${id}`)
      console.log(res)
      // 判断是否请求响应陈功
      if (res.meta.status !== 200) return this.$message('操作失败，请稍后重试！')
      // 重新加载列表
      this.getUsersList()
      // 提示操作成功
      this.$message.success('删除成功!')
    },
    // 展示分配角色对话框
    async alloRolesDialog (userInfo) {
      this.userInfo = userInfo
      // 获取所有角色
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败！')
      this.rolesList = res.data
      // console.log(res)
      this.alloRolesDialogVisible = true
    },
    // 分配角色
    async alloRoles () {
      // 先排除未选中
      if (!this.newRole) return this.$message.error('请选择角色！')
      // 在发送新角色请求
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,
        {
          rid: this.newRole
        })
      // 请求成功和失败
      if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
      // 更新视图
      this.getUsersList()
      // 关闭弹窗
      this.alloRolesDialogVisible = false
      // 提示成功
      this.$message.success('分配角色成功！')
    },
    // 关闭分配角色对话框事件
    alloRolesClose () {
      this.userInfo = {}
      this.newRole = ''
    }
  }
}
</script>

<style>
</style>
